/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package android.isisufes.home2;

import java.io.StringReader;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

import org.xml.sax.InputSource;

import android.app.Activity;
import android.content.Context;
import android.isisufes.R;
import android.isisufes.newclasses.Chat;
import android.isisufes.newclasses.ChatMessage;
import android.isisufes.util.ServerCom;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class ChatManager extends Activity{

	private EditText et;
	private ListView lv;
	private Timestamp lastDate = null;
	private long campaignId;
	private ChatAdapter ca;
	private List<ChatMessage> vetMsg = new ArrayList<ChatMessage>();
	private Timer chatPollingTimer;
	private static final int CHAT_POLLING_PERIOD = 10000;
	private MessageHandler mHandler;
	
	private class MessageHandler extends Handler{
		public static final int MESSAGE_UPDATEUI = 1;

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == MESSAGE_UPDATEUI){
				ca.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);
		campaignId = this.getIntent().getExtras().getLong("campaignId");
		
		lv = (ListView) findViewById(R.id.messageList);
		et = (EditText) findViewById(R.id.message);
		
		ca = new ChatAdapter(this, R.layout.message, vetMsg);
		lv.setAdapter(ca);
		
		//Pede ao servidor e lê as mensagens iniciais
		String initXml = ServerCom.getChatMessages(campaignId);
		Vector<ChatMessage> vetNew = Chat.parse(new InputSource(new StringReader(initXml)));
		//Pegando a última data
		if (!vetNew.isEmpty()){
			lastDate = vetNew.lastElement().getDateSent();
			//Atualizando a tela
			vetMsg.addAll(vetNew);
		}
		
		mHandler = new MessageHandler();
		
		chatPollingTimer = new Timer();
		chatPollingTimer.scheduleAtFixedRate(new chatPollingTask(), CHAT_POLLING_PERIOD, CHAT_POLLING_PERIOD);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		chatPollingTimer.cancel();
	}

	public void sendMessage(View v) {
		String msg = et.getText().toString();
		
		if(msg.length() == 0){
			return;
		}
		
		et.setText("");

		String xml = ServerCom.sendAndGetChatMessages(campaignId, lastDate, msg);
		Vector<ChatMessage> vetNew = Chat.parse(new InputSource(new StringReader(xml)));
		//Pegando a última data
		if(!vetNew.isEmpty()){
			lastDate = vetNew.lastElement().getDateSent();
			//Atualizando a tela
			vetMsg.addAll(vetNew);
			ca.notifyDataSetChanged();
		}
    }
	
	private class ChatAdapter extends ArrayAdapter<ChatMessage> {
		private List<ChatMessage> vetMsg;
		
		public ChatAdapter(Context context, int textViewResourceId, List<ChatMessage> items) {
			super(context, textViewResourceId, items);
			this.vetMsg = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.message, null);
			}

			ChatMessage cm = vetMsg.get(position);
			if (cm != null) {
				((TextView) v.findViewById(R.id.date)).setText(cm.getDateSent().toString().substring(0, 19));
				((TextView) v.findViewById(R.id.sender)).setText(cm.getSender());
				((TextView) v.findViewById(R.id.body)).setText(cm.getMessageBody());
			}
			return v;
		}
	}
	
	private class chatPollingTask extends TimerTask {
		@Override
		public void run() {
			String xml;
			
			if(lastDate != null){
				//Chama o Updater
				xml = ServerCom.getChatMessages(campaignId, lastDate);
			}else{
				//Chama o init denovo
				xml = ServerCom.getChatMessages(campaignId);
			}
			
			Vector<ChatMessage> vetNew = Chat.parse(new InputSource(new StringReader(xml)));
			if(!(vetNew.isEmpty())){
				lastDate =  vetNew.lastElement().getDateSent();
				vetMsg.addAll(vetNew);
				Message msg = new Message();
				msg.what = MessageHandler.MESSAGE_UPDATEUI;
				mHandler.sendMessage(msg);
			}
			
		}
	}
}
